<?php
header('Content-Type: application/json');

try {
    $booksFile = '../../data/books.json';
    
    if (!file_exists($booksFile)) {
        throw new Exception('books.json 文件不存在');
    }
    
    $content = file_get_contents($booksFile);
    if ($content === false) {
        throw new Exception('无法读取 books.json 文件');
    }
    
    $books = json_decode($content, true);
    $jsonError = json_last_error();
    
    if ($jsonError !== JSON_ERROR_NONE) {
        throw new Exception('JSON 解析失败: ' . json_last_error_msg());
    }
    
    if (!isset($books['books']) || !is_array($books['books'])) {
        throw new Exception('books.json 格式错误：缺少 books 数组');
    }
    
    echo json_encode(['success' => true, 'data' => $books]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => $e->getMessage(),
        'debug' => [
            'file' => $booksFile,
            'exists' => file_exists($booksFile),
            'size' => file_exists($booksFile) ? filesize($booksFile) : 0,
            'content' => file_exists($booksFile) ? substr(file_get_contents($booksFile), 0, 1000) : null
        ]
    ]);
}
